# -*- coding = utf-8 -*-
# @Time    : 2025/4/9 上午10:42
# @Author  : yqk
# @File    : CaptchaSolver.py.py
# @Software: PyCharm
# CaptchaSolver.py
import cv2
import requests
import re

class CaptchaSolver:
    def __init__(self, image_url):
        self.image_url = image_url
        self.image_path = "captcha_image.jpg"
        self.download_image()

    def download_image(self):
        req = requests.get(self.image_url)
        with open(self.image_path, "wb") as file:
            file.write(req.content)

    # 定义一个处理图片缺口的函数，最后返回x坐标，滑块移动不需要y坐标
    def get_pos(self, image):
        # 首先使用高斯模糊去噪，噪声会影响边缘检测的准确性，因此首先要将噪声过滤掉
        blurred = cv2.GaussianBlur(image, (5, 5), 0, 0)

        # 边缘检测，得到图片轮廓
        canny = cv2.Canny(blurred, 200, 400)

        # 轮廓检测
        contours, hierarchy = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        for contour in contours:
            M = cv2.moments(contour)  # 并计算每一个轮廓的力矩(Moment)，就可以得出物体的质心位置
            if M['m00'] == 0:
                cx = cy = 0
            else:
                cx, cy = M['m10'] / M['m00'], M['m01'] / M['m00']

            # 判断轮廓是否在面积和周长的范围内
            if 5000 < cv2.contourArea(contour) < 8000 and 300 < cv2.arcLength(contour, True) < 500:
                if cx < 300:
                    continue
                # 外接矩形，x，y是矩阵左上点的坐标，w，h是矩阵的宽和高
                x, y, w, h = cv2.boundingRect(contour)
                return x  # 返回x坐标
        return 0

    # 获取滑块位置的接口
    def get_slider_position(self):
        # 读取图片
        verify_img = cv2.imread(self.image_path)
        # 调用get_pos函数，得到x坐标
        return self.get_pos(verify_img)
